<?php
namespace app\api\controller;
use app\common\controller\ApiBase;
use app\common\library\ErrorType;
use app\common\model\User;
use think\facade\Cache;
use yu\Random;

/**
 * @title Login
 * @description 用户登录相关类
 * @package app\api\controller
 */
class Login extends ApiBase
{
    /**
     * @title 邮箱登录
     * @description 邮箱登录
     * @author Admin ldy
     * @url /api/login/maillogin
     * @param name:email  type:string require:1 default:1 desc: 邮箱
     * @param name:pwd  type:string require:1 default:1 desc: 密码
     * @time 2018/9/18  15:26
     */
    public function mailLogin(){
        $email = $this->request->param('email');
        $password = $this->request->param('pwd');
        $data = [
            'email' => $email,
            'password'=>$password,
        ];
        $validate = new \app\common\validate\User;
        if (!$validate->scene('mailLogin')->check($data)) {
            $this->error($validate->getError());
        }
        $user = \app\common\model\User::getByEmail($email);
        if (!$user){
            $this->error('用户信息有误！');
        }
        if ($user -> password != md5($password)){
            $this->error('用户信息有误！');
        }
        $uid = $user->id;

        $token = Random::uuid_yu();
        //token设置有效期为30天
        \cache($token,$uid,60*60*24*30,'login-token');
        $result['token'] = $token;
        $result['user']=$user;
        $this->success('登录成功！',$result,200);
    }



    public function loginOut(){
        $token = $this->request->param('token');
        $re = $this->clearUidByToken($token);
        if ($re){
            $this->success('退出登录成功',$re,200);
        }else{
            $this->err(ErrorType::ACTION_FAILED);
        }
    }

    /**
     * @title token验证
     * @description token验证
     * @author Admin ldy
     * @url /api/login/checkToken
     * @param name:token  type:string require:1 default:1 desc:
     * @time 2018/9/18  16:19
     */
    public function checkToken(){
        $uid=$this->getUidByCheck();
        $this->success('token有效',$uid);
    }

    /**
     * @title 测试方法
     * @description 测试方法
     * @author Admin ldy
     * @url /api/login/tes
     * @param name:email  type:string require:1 default:1 desc:
     * @time 2018/9/18  15:30
     */
    public function tes(){
        $modulename = $this->request->module();
        $controllername = strtolower($this->request->controller());
        $actionname = strtolower($this->request->action());
        $path = '/'.$modulename.'/'.str_replace('.', '/', $controllername) . '/' . $actionname;
        $email = '455@qq.com';
        $user = \app\common\model\User::getByEmail($email);

        $this->success('chenggong',$user);
    }



}
